﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;
using System.Text.RegularExpressions;
using System.Globalization;

namespace SSMS
{
    public partial class Main : Form
    {

        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            string url = String.Format("http://192.168.118.188:{0}/Mobile.svc/", 18741);
            //测试
            //string url = String.Format("http://192.168.1.112:{0}/Mobile.svc/", 18741);
            Uri baseAddress = new Uri(url);
            ServiceHost host = new ServiceHost(typeof(MobileApi), baseAddress);

            host.AddServiceEndpoint(typeof(IMobileApi), new BasicHttpBinding(), "");
            ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
            behavior.HttpGetEnabled = true;
            behavior.HttpGetUrl = new Uri(url);
            host.Description.Behaviors.Add(behavior);
            try
            {
                host.Open();
                MessageBox.Show("功能接口发布成功");
            }
            catch (Exception ex)
            {
            }
        }
    }
    public class MobileApi : IMobileApi
    {
        SqlConnection conn = DB.MyCon;
        SqlDataAdapter da;
        JObject json;
        JObject purchaseJson;//其他入库单json
        string tempBillNo;//插入数据的单号
        string purchaseBillNo;//其他入库单单据号
        DataSet ds = new DataSet();
        DataView dv = new DataView();
        
        /// <summary>
        /// 用户登录信息验证
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public String UserLogin(string encrypt)
        {
            XModeRtn result = new XModeRtn();
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String username = jo["Data"]["Data"]["username"].ToString();
            String password = jo["Data"]["Data"]["password"].ToString();
            //查询该用户名密码是否存在，并封装到用户表User中t_AppUser

            //DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
            //dtFormat.ShortDatePattern = "yyyy-MM-dd hh:mm:ss";
            //DateTime dt = Convert.ToDateTime("20170291", dtFormat);
            User  loginUser = CheckLoginUser(username, password);
            if (loginUser == null)
            {
                result["state"] = "error";
                result["message"] = "用户名或密码错误";
            }
            else
            {
                result["state"] = "ok";
                result.JsonObject = (String)JsonConvert.SerializeObject(loginUser);
                result.ObjectType = typeof(User).FullName;
            }
            //return result.ToString();
            return (String)JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 获取计划单信息
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public String SalesPlanList(string encrypt)
        {
            XModeRtn result = new XModeRtn();
            XModeMsg msg = new XModeMsg();
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String searchContent = jo["Data"]["Data"]["searchContent"].ToString();
            String startDate = jo["Data"]["Data"]["startDate"].ToString();
            String planState = jo["Data"]["Data"]["planState"].ToString();
            String setGang = jo["Data"]["Data"]["setGang"].ToString();
            //String type = jo["Data"]["Data"]["type"].ToString();
            StringBuilder sb = new StringBuilder("");
            if (!setGang.Equals("")) 
            {
                sb.Append(" and A.FComboBox4 ='" + setGang + "'");
            }
            if (!startDate.Equals(""))
            {
                sb.Append(" and A.FDate>='" + startDate + " 00:00:00'");
            }
            if (!planState.Equals(""))
            {
                sb.Append(" and A.FComboBox2=" + planState);
            }
            if (!searchContent.Equals(""))
            {
                sb.Append(" and (A.FText like '%" + searchContent + "%' or C.FName like '%" + searchContent + "%' )");
            }
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            string sqlTT = " select A.FID, A.FBillNo BillNo,A.FText ShipName,A.FDecimal PreQty,A.FDecimal9 AuxQty,A.FDate PlanTime,A.FTime2 SuttleTime,C.FName CustomerName,B.FName ProductName, " +
                            "(case  when(A.FComboBox2=0)  then '未使用' when(A.FComboBox2=1)  then '已使用' when(A.FComboBox2=2)  then '已作废' when(A.FComboBox2=3)  then '已归档' end) PlanState " +
                            "from KEW_SalesPlan A " +
                            "left join  KEW_Products B on A.FBase1=B.FID " +
                            "left join  t_Organization C on A.FBase=C.FItemID " +                           
                            "where 1=1 "+sb.ToString()+" order by A.FID DESC ";
            da = new SqlDataAdapter(sqlTT, conn);
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count < 0)
            {
                msg.Type = MessageType.Warning;
                msg.Note = String.Format("销售计划信息不存在");
                result["state"] = "error";
                result["message"] = msg.Note;
                result.JsonObject = "NonExit";
                return (String)JsonConvert.SerializeObject(result);
            }
            List<AppSalesPlan> plans = new List<AppSalesPlan>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                AppSalesPlan plan = new AppSalesPlan();
                plan.FID = row["FID"].ToString();
                plan.BillNo = row["BillNo"].ToString();
                plan.ShipName = row["ShipName"].ToString();
                plan.PreQty = (decimal)row["PreQty"];
                plan.AuxQty = (decimal)row["AuxQty"];
                plan.PlanTime = row["PlanTime"].ToString();
                plan.CustomerName = row["CustomerName"].ToString();
                plan.ProductName = row["ProductName"].ToString();
                plan.PlanState = row["PlanState"].ToString();
                plans.Add(plan);
            }
            msg.Type = MessageType.Note;
            msg.Note = String.Format("获取计划单成功");
            result["state"] = "ok";
            result.JsonObject = (String)JsonConvert.SerializeObject(plans);
            result.ObjectType = typeof(List<AppSalesPlan>).FullName;
            result["message"] = msg.Note;
            return (String)JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 获取计量单信息
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public String SalesInfoList(string encrypt)
        {
            XModeRtn result = new XModeRtn();
            XModeMsg msg = new XModeMsg();
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String searchContent = jo["Data"]["Data"]["searchContent"].ToString();
            String startDate = jo["Data"]["Data"]["startDate"].ToString();
            String infoState = jo["Data"]["Data"]["infoState"].ToString();
            //String type = jo["Data"]["Data"]["type"].ToString();
            StringBuilder sb = new StringBuilder("");
            if (!startDate.Equals(""))
            {
                sb.Append(" and A.FTime>='" + startDate + " 00:00:00'");
            }
            if (!infoState.Equals(""))
            {
                if (infoState.Equals("-1"))
                {
                    sb.Append(" and A.FCheckBox4=1");
                }
                else if (infoState.Equals("4"))
                {
                    sb.Append(" and A.FCheckBox8=1");
                }
                else
                {
                    sb.Append(" and A.FComboBox="+infoState);
                }

            }
            if (!searchContent.Equals(""))
            {
                sb.Append(" and (B.FName like '%" + searchContent + "%' or C.FName like '%" + searchContent + "%' )");
            }
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            string sqlTT = " select A.FID, A.FBillNo BillNo,A.FText CarNo,A.FDecimal4 PreQty,A.FDecimal2 AuxSuttle,A.FTime1 FistTime,A.FTime2 SecondTime,A.FText16 ShipName,C.FName CustomerName,B.FName ProductName, " +
                            "(case when(A.FCheckBox4=1)  then '已作废' when(A.FCheckBox8=1)  then '已签收' when(A.FComboBox=-1)  then '授权发货' when(A.FComboBox=0)  then '开票' when(A.FComboBox=1)  then '已开票' when(A.FComboBox=2)  then '已进厂计量' when(A.FComboBox=3)  then '计量完成' end) InfoState " +
                            "from KEW_SalesInfo A " +
                            "left join  KEW_Products B on A.FBase=B.FID " +
                            "left join  t_Organization C on A.FBase1=C.FItemID " +
                            "where FComboBox4=1 " + sb.ToString() + " order by A.FID desc ";
            da = new SqlDataAdapter(sqlTT, conn);
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count < 0)
            {
                msg.Type = MessageType.Warning;
                msg.Note = String.Format("销售计量单信息不存在");
                result["state"] = "error";
                result["message"] = msg.Note;
                result.JsonObject = "NonExit";
                return (String)JsonConvert.SerializeObject(result);
            }
            List<AppSalesInfo> infos = new List<AppSalesInfo>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                AppSalesInfo item = new AppSalesInfo();
                item.FID = (int)row["FID"];
                item.BillNo = row["BillNo"].ToString();
                item.CarNumber = row["CarNo"].ToString();
                item.ContianerNum = row["ShipName"].ToString();//关联船号
                //item.PreQty = (decimal)row["PreQty"];
                item.AuxSuttle = (decimal)row["AuxSuttle"];
                item.FistTime = row["FistTime"].ToString();
                item.SecdTime = row["SecondTime"].ToString();
                item.CustomerName = row["CustomerName"].ToString();
                item.ItemName = row["ProductName"].ToString();
                item.Step = row["InfoState"].ToString();
                infos.Add(item);
            }
            msg.Type = MessageType.Note;
            msg.Note = String.Format("获取计量单成功");
            result["state"] = "ok";
            result.JsonObject = (String)JsonConvert.SerializeObject(infos);
            result.ObjectType = typeof(List<AppSalesPlan>).FullName;
            result["message"] = msg.Note;
            return (String)JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 更新计划单状态
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public String UpdateSalesPlan(string encrypt)
        {
            XModeRtn result = new XModeRtn();
            XModeMsg msg = new XModeMsg();
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
            dtFormat.ShortDatePattern = "yyyy-MM-dd hh:mm:ss";
            String fid = jo["Data"]["Data"]["fid"].ToString();
            String planState = jo["Data"]["Data"]["planState"].ToString();
            StringBuilder sb = new StringBuilder("select * from kew_salesPlan where fid="+fid);
            if (fid.Equals("") || planState.Equals(""))
            {
                msg.Type = MessageType.Warning;
                msg.Note = String.Format("未获取计划信息");
                result["state"] = "error";
                result["message"] = msg.Note;
                result.JsonObject = "NonExit";
                return (String)JsonConvert.SerializeObject(result);
            }
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            String sqlUpdate = "";
            if (planState.Equals("1"))//反归档
            {
                sb.Append("and FComboBox2=3 ");
                sqlUpdate = "update kew_salesPlan set FComboBox2=" + planState + " where fid=" + fid;
            }
            else 
            {
                sb.Append("and FComboBox2=1 ");
                sqlUpdate = "update kew_salesPlan set FComboBox2=" + planState + ",FTime2='" + Convert.ToDateTime(DateTime.Now.ToLocalTime().ToString(), dtFormat) + "' where fid=" + fid;
            }
            da = new SqlDataAdapter(sb.ToString(), conn);
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count <= 0)
            {
                msg.Type = MessageType.Warning;
                msg.Note = String.Format("销售计划不存在或状态不正确");
                result["state"] = "error";
                result["message"] = msg.Note;
                result.JsonObject = "NonState";
                return (String)JsonConvert.SerializeObject(result);
            }
            SqlCommand comm = new SqlCommand(sqlUpdate, conn);
            comm.ExecuteNonQuery();
            ds.Clear();
            String sql2 = "select * from  kew_salesPlan where FComboBox2=" + planState + " and  fid=" + fid;
            da = new SqlDataAdapter(sql2, conn);
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count == 1)
            {
                msg.Type = MessageType.Note;
                msg.Note = String.Format("更新计划单成功");
                result["state"] = "ok";
                result.JsonObject = planState;
                result["message"] = msg.Note;
            }
            else
            {
                result["state"] = "Error";
                msg.Type = MessageType.Warning;
                msg.Note = String.Format("更新FID号为[{0}]的计划单失败！", fid);
                result.JsonObject = "error";
                result["message"] = msg.Note;
            }
            return (String)JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 获取计量单信息
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public String GetSalesInfoByPlanID(string encrypt)
        {
            XModeRtn result = new XModeRtn();
            XModeMsg msg = new XModeMsg();
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String planId = jo["Data"]["Data"]["planId"].ToString();
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            string sqlTT = " select A.FID, A.FBillNo BillNo,A.FText CarNo,A.FDecimal4 PreQty,A.FDecimal2 AuxSuttle,A.FTime1 FistTime,A.FTime2 SecondTime,A.FText16 ShipName,C.FName CustomerName,B.FName ProductName, " +
                "(case when(A.FCheckBox4=1)  then '已作废' when(A.FCheckBox8=1)  then '已签收' when(A.FComboBox=-1)  then '授权发货' when(A.FComboBox=0)  then '开票' when(A.FComboBox=1)  then '已开票' when(A.FComboBox=2)  then '已进厂计量' when(A.FComboBox=3)  then '计量完成' end) InfoState " +
                "from KEW_SalesInfo A " +
                "left join  KEW_Products B on A.FBase=B.FID " +
                "left join  t_Organization C on A.FBase1=C.FItemID " +
                "where A.FComboBox4=1 and A.FID_SRC1=" + planId + " order by A.FTime2  ";
            da = new SqlDataAdapter(sqlTT, conn);
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count < 0)
            {
                msg.Type = MessageType.Warning;
                msg.Note = String.Format("销售计量信息不存在");
                result["state"] = "error";
                result["message"] = msg.Note;
                result.JsonObject = "NonExit";
                return (String)JsonConvert.SerializeObject(result);
            }
            List<AppSalesInfo> infos = new List<AppSalesInfo>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                AppSalesInfo item = new AppSalesInfo();
                item.FID = (int)row["FID"];
                item.BillNo = row["CarNo"].ToString();//用于显示出车牌号，与磁卡读取页面区别
                item.CarNumber = row["CarNo"].ToString();
                item.ContianerNum = row["ShipName"].ToString();//关联船号
                //item.PreQty = (decimal)row["PreQty"];
                item.AuxSuttle = (decimal)row["AuxSuttle"];
                item.FistTime = row["FistTime"].ToString();
                item.SecdTime = row["SecondTime"].ToString();
                item.CustomerName = row["CustomerName"].ToString();
                item.ItemName = row["ProductName"].ToString();
                item.Step = row["InfoState"].ToString();
                infos.Add(item);
            }
            msg.Type = MessageType.Note;
            msg.Note = String.Format("获取销售计量单成功");
            result["state"] = "ok";
            result.JsonObject = (String)JsonConvert.SerializeObject(infos);
            result.ObjectType = typeof(List<AppSalesInfo>).FullName;
            result["message"] = msg.Note;
            return (String)JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 获取计量单信息
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public String GetSalesInfoByCardID(string encrypt)
        {
            XModeRtn result = new XModeRtn();
            XModeMsg msg = new XModeMsg();
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String cardId = jo["Data"]["Data"]["cardId"].ToString();
            String setGang = jo["Data"]["Data"]["setGang"].ToString();
            StringBuilder sb = new StringBuilder("");
            if (!setGang.Equals("")) 
            {
                sb.Append(" and F.FComboBox4 ='" + setGang + "'");
            }
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            string sqlTT = " select A.FID, A.FBillNo BillNo,A.FText CarNo,A.FDecimal4 PreQty,A.FDecimal2 AuxSuttle,A.FTime1 FistTime,A.FTime2 SecondTime,A.FText16 ShipName,C.FName CustomerName,B.FName ProductName, " +
                            "(case when(A.FCheckBox4=1)  then '已作废' when(A.FCheckBox8=1)  then '已签收' when(A.FComboBox=-1)  then '授权发货' when(A.FComboBox=0)  then '开票' when(A.FComboBox=1)  then '已开票' when(A.FComboBox=2)  then '已进厂计量' when(A.FComboBox=3)  then '计量完成' end) InfoState " +
                            "from KEW_SalesInfo A " +
                            "left join  KEW_Products B on A.FBase=B.FID " +
                            "left join  t_Organization C on A.FBase1=C.FItemID " +
                            "left join  KEW_PortCard D on A.FText=D.FText " +
                            "left join  CardServer.DBO.KEW_ICCardEntry E on D.FText1=E.FNumber " +
                            "left join KEW_SalesPlan F on A.FBillNo_SRC1=F.FBillNo "+
                            "where E.FText='" + cardId + "'"+sb.ToString()+" AND A.FComboBox4=1 AND A.FCheckBox4=0 AND A.FComboBox=3 and A.FCheckBox8=0 order by A.FID DESC ";
                            //"where E.FText='" + cardId + "'" + sb.ToString() + "  order by A.FID DESC ";
                            //"where 1=1 " + sb.ToString() + "  order by A.FID DESC ";
            da = new SqlDataAdapter(sqlTT, conn);
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count < 0)
            {
                msg.Type = MessageType.Warning;
                msg.Note = String.Format("销售计量信息不存在");
                result["state"] = "error";
                result["message"] = msg.Note;
                result.JsonObject = "NonExit";
                return (String)JsonConvert.SerializeObject(result);
            }
            List<AppSalesInfo> infos = new List<AppSalesInfo>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                AppSalesInfo item = new AppSalesInfo();
                item.FID = (int)row["FID"];
                item.BillNo = row["BillNo"].ToString();
                item.CarNumber = row["CarNo"].ToString();
                item.ContianerNum = row["ShipName"].ToString();//关联船号
                //item.PreQty = (decimal)row["PreQty"];
                item.AuxSuttle = (decimal)row["AuxSuttle"];
                item.FistTime = row["FistTime"].ToString();
                item.SecdTime = row["SecondTime"].ToString();
                item.CustomerName = row["CustomerName"].ToString();
                item.ItemName = row["ProductName"].ToString();
                item.Step = row["InfoState"].ToString();
                infos.Add(item);
            }
            msg.Type = MessageType.Note;
            msg.Note = String.Format("获取销售计量单成功");
            result["state"] = "ok";
            result.JsonObject = (String)JsonConvert.SerializeObject(infos);
            result.ObjectType = typeof(List<AppSalesInfo>).FullName;
            result["message"] = msg.Note;
            return (String)JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 更新计量单状态
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public String SalesInfoSign(string encrypt)
        {
            XModeRtn result = new XModeRtn();
            XModeMsg msg = new XModeMsg();
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String infoId = jo["Data"]["Data"]["infoId"].ToString();
 
            if (infoId.Equals(""))
            {
                msg.Type = MessageType.Warning;
                msg.Note = String.Format("未获取计量单信息");
                result["state"] = "error";
                result["message"] = msg.Note;
                result.JsonObject = "NonExit";
                return (String)JsonConvert.SerializeObject(result);
            }
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            String sqlSel = "select * from kew_salesInfo where fid=" + infoId + "and FComboBox=3 ";
            da = new SqlDataAdapter(sqlSel, conn);
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count <= 0)
            {
                msg.Type = MessageType.Warning;
                msg.Note = String.Format("非计量完成单据不能进行归档");
                result["state"] = "error";
                result["message"] = msg.Note;
                result.JsonObject = "NonState";
                return (String)JsonConvert.SerializeObject(result);
            }
            String sqlUpdate = "update kew_salesInfo set FCheckBox8=1 where fid=" + infoId;
            SqlCommand comm = new SqlCommand(sqlUpdate, conn);
            comm.ExecuteNonQuery();
            ds.Clear();
            String sql2 = "select * from  kew_salesInfo where FCheckBox8=1 and  fid=" + infoId;
            da = new SqlDataAdapter(sql2, conn);
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count == 1)
            {
                msg.Type = MessageType.Note;
                msg.Note = String.Format("FID号为[{0}]的签收成功！", infoId);
                result["state"] = "ok";
                result.JsonObject = "ok";
                result["message"] = msg.Note;
            }
            else
            {
                result["state"] = "Error";
                msg.Type = MessageType.Warning;
                msg.Note = String.Format("FID号为[{0}]的签收失败！", infoId);
                result.JsonObject = "error";
                result["message"] = msg.Note;
            }
            return (String)JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 根据用户名、密码查询用户信息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public User CheckLoginUser(string username, string password)
        {
            string sql = "select * from t_AppUser  where isuse=1 and username='" + username + "' and password='" + password + "'";
            try
            {
                da = new SqlDataAdapter(sql, conn);
                da.Fill(ds);
                //判断账号密码是否正确
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    User user = new User();
                    user.id = (decimal)row["id"];
                    user.username = username;
                    user.password = password;
                    user.authorityType = (string)row["authorityType"];
                    user.userauthority = (int)row["userauthority"];
                    //return JsonConvert.SerializeObject(user).ToString();
                    return user;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 根据名称或id获取用户信息
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public String getUserByNameorId(string encrypt)
        {
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String type = jo["Data"]["Data"]["type"].ToString();
            DataTable dt;
            string sql = "select *  from t_AppUser where useritemid='" + type + "' or username like '%" + type + "%' order by id desc ";
            try
            {
                da = new SqlDataAdapter(sql, conn);
                da.Fill(ds);
                if (ds != null && ds.Tables[0] != null)
                {
                    dt = ds.Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        return JsonConvert.SerializeObject(dt).ToString();
                    }
                }
                else
                {
                    return "fail";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "fail";
            }
            return "fail";
        }
        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public string addUsers(string encrypt)
        {
            string returnValue = "fail";
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);

            String p_json = jo["Data"]["Data"]["p_json"].ToString();
            JObject jobj = (JObject)JsonConvert.DeserializeObject(p_json);

            String userName = jobj["userName"].ToString();//用户名
            String password = jobj["password"].ToString();//密码
            int roles = int.Parse(jobj["roles"].ToString());//权限
            String authorityType = jobj["authorityType"].ToString();//职位
            //判断用户名是否存在
            string sql = "select *  from t_AppUser where username like '%" + userName + "%'";
            try
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                da = new SqlDataAdapter(sql, conn);
                da.Fill(ds);
                if (ds != null && ds.Tables[0] != null)
                {
                    DataTable dt = ds.Tables[0];
                    //存在该用户名
                    if (dt.Rows.Count > 0)
                    {
                        return "exist";
                    }
                    //插入数据
                    else
                    {
                        string sql1 = "insert into t_AppUser(username, password, userauthority, authorityType) values ('" + userName + "', '" + password + "', " + roles + ", '" + authorityType + "')";
                        //MessageBox.Show("输出语句为：" + sql1);
                        SqlCommand comm = new SqlCommand(sql1, conn);
                        comm.ExecuteNonQuery();
                        returnValue = "success";
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "fail";
            }
            finally
            {
                conn.Close();
            }
            return returnValue;
        }
        /// <summary>
        /// 更新用户信息，删除、重置密码
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public string updateUsers(string encrypt)
        {
            string returnValue = "fail";
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String p_json = jo["Data"]["Data"]["p_json"].ToString();
            JObject jobj = (JObject)JsonConvert.DeserializeObject(p_json);
            String type = jobj["type"].ToString();//类型，删除、重置、更新
            decimal userId = decimal.Parse(jobj["userId"].ToString());//用户id
            string sql = "";
            if (type.Equals("update"))
            {
                int roles = int.Parse(jobj["roles"].ToString());//权限
                String authorityType = jobj["authorityType"].ToString();//职位
                sql = "update t_AppUser set userAuthority=" + roles + ", authorityType='" + authorityType + "' where id=" + userId + "";
            }
            else if (type.Equals("delete"))
            {
                sql = "update t_AppUser set isuse=0 where id=" + userId + "";
            }
            else if (type.Equals("reset"))
            {
                String pwd = jobj["pwd"].ToString();//密码
                sql = "update t_AppUser set password='" + pwd + "' where id=" + userId + "";
            }
            try
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                SqlCommand comm = new SqlCommand(sql, conn);
                comm.ExecuteNonQuery();
                returnValue = "success";

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "fail";
            }
            finally
            {
                conn.Close();
            }
            return returnValue;
        }

        /// <summary>
        /// 手工校验生成入库单，打印二维码
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public String saveProductIn(string encrypt)
        {
            string returnValue = "fail";
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String p_json = jo["Data"]["Data"]["p_json"].ToString();
            JObject jobj = (JObject)JsonConvert.DeserializeObject(p_json);
            String isOk = jobj["isOk"].ToString();//判断合格or隔离
            //获取FInterID,执行存储过程
            String FInterID = "";
            //获取单号，执行存储过程
            String FBillNo = "";
            tempBillNo = FBillNo;

            int type = int.Parse(jobj["type"].ToString());//单据类型
            String classType = jobj["classType"].ToString();//班别，白班or 夜班
            String deptid = jobj["deptid"].ToString();//部门
            String accepterId = jobj["accepterId"].ToString();//验收人
            String custodianId = jobj["custodianId"].ToString();//保管人
            String productId = jobj["productid"].ToString();//商品ID
            String productName = jobj["productname"].ToString();//商品name
            String number = jobj["number"].ToString();//数量
            String batch = jobj["batch"].ToString();//批次
            String productLine = jobj["productLine"].ToString();//生产线别
            String packingLine = jobj["packingLine"].ToString();//包装线别
            String boardNumber = jobj["boardNumber"].ToString();//板号
            String starttime = jobj["starttime"].ToString();//开始时间
            String endtime = jobj["endtime"].ToString();//结束时间
            String cupInfo = jobj["cupInfo"].ToString();//水杯信息
            String productBatch = jobj["productBatch"].ToString();//生产批次信息
            String specification2 = jobj["specification2"].ToString();//规格2
            String specification3 = jobj["specification3"].ToString();//规格3
            //根据物料编码加载出物料的基本信息，FDCStockID调入仓库，FUnitID单位内码，AuxPrice单位成本，FDetailID分录内码，检验是否为良品
            //根据物料编码查询出物料基本信息，单位，仓库等
            //查询出该物料基本信息，单位、仓库等
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            //先判断该板号是否存在，生成入库单
            string sqlCheck = "";
            string batchTemp = "";
            if (type == 0)
            {
                batchTemp = batch;
                sqlCheck = "select top 1 * from t_AppProductInBill where productId='" + productId + "' and productLine='" + productLine + "' and boardNum='" + boardNumber + "' and batch='" + batch + "'";
            }
            else
            {
                batchTemp = productBatch;
                number = (Int32.Parse(number) * Int32.Parse(specification3)).ToString();
                sqlCheck = "select top 1 * from t_AppProductInBill where productId='" + productId + "' and packingLine='" + packingLine + "' and boardNum='" + boardNumber + "' and productBatch='" + batchTemp + "'";
            }

            da = new SqlDataAdapter(sqlCheck, conn);
            da.Fill(ds);
            //如果存在，返回提示存在
            if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                return "exist";
            }
            ds.Clear();
            string sqlTT = " select top 1 * from t_icitem where FUseState=341 and FItemID= " + productId;
            da = new SqlDataAdapter(sqlTT, conn);
            da.Fill(ds);
            int unitId = 249;//罐或件,297
            int dcStockId = 0;//存入仓库
            if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows != null && ds.Tables[0].Rows.Count > 0)
            {
                unitId = (int)ds.Tables[0].Rows[0]["FUnitID"];
                dcStockId = (int)ds.Tables[0].Rows[0]["FDefaultLoc"];
            }

            //无论合格、隔离，都生成清单、入库单最后执行打印操作

            //生成app单据同时生成入库单，将其放到事务中执行

            SqlCommand cmd = new SqlCommand();
            SqlTransaction sqltran = conn.BeginTransaction();//用的SQLite数据库，其他数据库相应变化
            cmd.Connection = conn;
            cmd.Transaction = sqltran;
            try
            {
                //日期转换
                DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
                dtFormat.ShortDatePattern = "yyyy-MM-dd hh:mm:ss";
                //插入APP单据
                DateTime now = Convert.ToDateTime(DateTime.Now.ToLocalTime().ToString(), dtFormat);
                DateTime rq = DateTime.ParseExact(batch, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                DateTime addTime = Convert.ToDateTime(rq.ToString("yyyy-MM-dd ") + endtime, dtFormat);
                string sql = "insert into t_AppProductInBill(billType,billNo, productId, productName, batch,receiveDept,productLine, packingLine, amount, boardNum,startTime,endTime,cupInfo,productBatch,specification2,specification3,billTime,classType,isOk) values (" +
                            type + ", '" + FBillNo + "', '" + productId + "', '" + productName + "', '" + batch + "', '" + deptid + "', '" + productLine + "', '" + packingLine + "', " + number + ", '" + boardNumber + "', '" + starttime + "','" + endtime + "','" + cupInfo + "','" + productBatch + "','" + specification2 + "','" + specification3 + "','" + addTime + "','" + classType + "'," + isOk + ")";
                //MessageBox.Show("输出语句为sql：" + sql);
                //SqlCommand comm = new SqlCommand(sql, conn);
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();

                //表头插入数据
                //公司机构代码，ID,单据类型，单据日期,单号，部门，验收人，保管人,制单人ID,FROB 红蓝字1,-1红字，FStatus审核1未审核0,FUpStockWhenSave0审核时1保存时更新库存,FCancellation0未作废1已作废,FOrgBillInterID源单内码
                //FBackFlushed0倒充标识,FWBInterID0工序计划单内码,FTranStatus0传输状态,FPurposeID领料类型,FSelTranType源单类型,FCheckDate审核日期，FMarketingStyle销售业务类型12530，
                string sql1 = string.Format("insert into ICStockBill(FBrNo,FInterID,FTranType,FDate,FBillNo,FDeptId,FFManagerID,FSManagerID,FHookInterID,FVchInterID,FPosted,FCheckSelect,FROB,FUpStockWhenSave,FCancellation,FOrgBillInterID" +
                    ",FBackFlushed,FWBInterID,FTranStatus,FPurposeID,FSelTranType,FCheckDate,FMarketingStyle,FStatus,FCheckerID ) values (0," + FInterID + ",2,'" + rq + "','" + FBillNo + "'," + deptid + "," + accepterId + "," + custodianId + ",0,0,0,0,1,1,0,0" +
                    ",0,0,0,0,85,'" + now + "',12530,1," + custodianId + ")");
                cmd.CommandText = sql1;
                cmd.ExecuteNonQuery();

                //表体插入数据
                string sql2 = string.Format("insert into ICStockBillEntry(FBrNo,FInterID,FEntryID,FItemID,FQty,FAuxQty,FUnitID,FDCStockID,FChkPassItem,FBatchNo,FNote) values (0," + FInterID + ",1," + productId + "," + number + "," + number + "," + unitId + "," + dcStockId + ",1058," + batchTemp + ",'" + boardNumber + "   " + endtime +"  " + classType + "')");//故意多添加一个值，看看错误
                //MessageBox.Show(sql2);
                cmd.CommandText = sql2;
                cmd.ExecuteNonQuery();


                //更新库存信息
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "C_UpDateICStockQtyBill";
                //传递一个输入参数,需要赋值
                SqlParameter sp = cmd.Parameters.Add("@FInterID", SqlDbType.Int);
                sp.Value = Int32.Parse(FInterID);
                sp = cmd.Parameters.Add("@ProssType", SqlDbType.Int);
                sp.Value = 0;
                cmd.ExecuteNonQuery();
                sqltran.Commit();//执行完要提交
                returnValue = "success";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);//抛出的异常消息
                sqltran.Rollback();//如果某条sql语句执行不成功，回滚
            }

            finally
            {
                conn.Close();
            }
            return returnValue;
        }

        /// <summary>
        /// 根据类型获取基本信息
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public String getBasicSelectData(string encrypt)
        {
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String type = jo["Data"]["Data"]["type"].ToString();
            //MessageBox.Show("类型为：" + type);
            DataTable dt = GetBasicDataByType(type);
            if (dt != null && dt.Rows.Count > 0)
            {
                return JsonConvert.SerializeObject(dt).ToString();
            }

            return "";
        }
        public DataTable GetBasicDataByType(string type)
        {
            string sql = "";
            switch (type)
            {
                case "purchaseUnit"://购货单位
                    sql = "select top 20 * from t_Organization  WHERE FDeleted=0  order by FShortNumber ";
                    break;
                case "mateterialsDept"://获取部门
                    sql = "select * from t_department where (FName like '包装%线' or FName like '车间_线' or FNumber like '09.0%' )  AND FDeleted=0  order by FNumber ";
                    break;
                case "productDept"://获取生产部门
                    sql = "select * from t_department where FName like '车间_线'  AND FDeleted=0 order by FNumber ";
                    break;
                case "packingDept"://获取包装部门
                    sql = "select * from t_department where FName like '包装%线'  AND FDeleted=0  order by FNumber ";
                    break;
                case "stockDept"://获取销售部门
                    sql = "select * from t_department where FNumber like '05.0%'  AND FDeleted=0  order by FNumber ";
                    break;
                case "processDept"://获取代加工部门
                    sql = "select * from t_department where FNumber like '09.0%'  AND FDeleted=0  order by FNumber ";
                    break;
                case "allDept"://获取所有部门
                    sql = "select * from t_department where (FName like '包装%线'  or FName like '车间_线'  or FName like '品质%'  or FName like '业务%')   AND FDeleted=0  order by FNumber ";
                    break;
                case "halfProduct"://半成品
                    sql = "select top 1000 * from t_icitem  where FNumber like '05.%'  AND FDeleted=0 and FUseState=341  order by FNumber ";//or FNumber like '05.04%' or FNumber like '05.14%'  or FNumber like '05.16%'  or FNumber like '05.11.011%'   or FNumber like '05.11.026%'  
                    break;
                case "product"://成品
                    sql = "select top 100 * from t_icitem   where (FNumber like '06.03%' or FNumber like '06.04%') AND FDeleted=0 and FUseState=341 order by FNumber ";
                    break;
                case "packMatetials"://包装物
                    sql = "select top 100 * from t_icitem   where FNumber like '08.03%' and FName like '伊利%礼盒%'  AND FDeleted=0  order by FNumber ";
                    break;
                case "packings"://包材
                    sql = "select top 100 * from t_icitem   where FNumber like '08.03%' and FName like '伊利%'  AND FDeleted=0  order by FNumber ";
                    break;
                case "emptyCan"://空罐
                    sql = "select top 100 * from t_icitem   where FNumber like '02.02%'  AND FDeleted=0  order by FNumber ";
                    break;
                case "rawerial"://原料
                    sql = "select top 100 * from t_icitem   where FNumber like '01.02%'  AND FDeleted=0  order by FNumber ";
                    break;
            }
            try
            {
                da = new SqlDataAdapter(sql, conn);
                da.Fill(ds);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    return dt;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }
        //根据表、单号获取领料信息
        public string searchMaterialsInfo(string encrypt)
        {
            DataTable dt;
            string sql = "";
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String p_json = jo["Data"]["Data"]["p_json"].ToString();
            JObject jobj = (JObject)JsonConvert.DeserializeObject(p_json);
            String type = jobj["type"].ToString();//类型，0半成品1包材2空罐3原料
            String viewName = jobj["viewName"].ToString();
            String billNo = jobj["billNo"].ToString();//入库单号
            if (!billNo.Equals(""))
            {

                sql = "select top 1 *  from " + viewName + " where billNo='" + billNo + "' order by id desc ";
            }
            else
            {
                String boardNo = jobj["boardNo"].ToString();//板号
                String deptid = jobj["deptid"].ToString();//部门
                String batchNo = jobj["batchNo"].ToString();//批次
                sql = "select top 1 *  from " + viewName + " where batch='" + batchNo + "' and boardNum='" + boardNo + "' and  FDeptID='" + deptid + "' order by id desc ";
                if (!type.Equals("0"))
                {
                    sql = "select top 1 *  from " + viewName + " where purchaseBatch='" + batchNo + "' and boardNum='" + boardNo + "' and  FDeptID='" + deptid + "' order by id desc ";
                }
            }
            try
            {
                da = new SqlDataAdapter(sql, conn);
                da.Fill(ds);
                if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows != null)
                {
                    dt = ds.Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        return JsonConvert.SerializeObject(dt).ToString();
                    }
                }
                else
                {
                    return "fail";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "fail";
            }
            return "fail";
        }
        /// <summary>
        /// 添加包材领取信息
        /// </summary>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        public string savePackingsBill(string encrypt)
        {
            string returnValue = "fail";
            JObject jo = (JObject)JsonConvert.DeserializeObject(encrypt);
            String p_json = jo["Data"]["Data"]["p_json"].ToString();
            JObject jobj = (JObject)JsonConvert.DeserializeObject(p_json);

            int packingsType = int.Parse(jobj["packingsType"].ToString());//类型
            String classType = jobj["classType"].ToString();//班别，白班夜班
            decimal employeeId = (decimal)jobj["employeeId"];//员工ID
            String employeeName = jobj["employeeName"].ToString();//员工姓名
            String packingsId = jobj["packingsId"].ToString();//包材ID
            String packingsName = jobj["packingsName"].ToString();//包材姓名
            String deptId = jobj["deptId"].ToString();//包装线ID
            String deptName = jobj["deptName"].ToString();//包装线
            int packingsAmount = int.Parse(jobj["packingsAmount"].ToString());//包材数量

            DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
            dtFormat.ShortDatePattern = "yyyy-MM-dd hh:mm:ss";
            DateTime addDate = Convert.ToDateTime(DateTime.Now.ToLocalTime().ToString(), dtFormat);

            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            try
            {
                string sql1 = "insert into t_AppGetPackings(packingsType, employeeId, employeeName, deptId, deptName, packingsId, packingsName, packingsAmount,billTime,classType) values (" + packingsType + "," + employeeId + ", '" + employeeName + "', '" + deptId + "', '" + deptName + "', '" + packingsId + "', '" + packingsName + "', " + packingsAmount + ",'" + addDate + "','" + classType + "')";
                //MessageBox.Show("输出语句为：" + sql1);
                SqlCommand comm = new SqlCommand(sql1, conn);
                comm.ExecuteNonQuery();
                returnValue = "success";

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "fail";
            }
            finally
            {
                conn.Close();
            }
            return returnValue;
        }
    }
        [ServiceContract()]
        public interface IMobileApi
        {
            /*
             * 
             * 用户操作
             */

            //用户登陆
            [OperationContract]
            string UserLogin(string encrypt);
            //根据用户名\ID获取用户信息
            [OperationContract]
            string getUserByNameorId(string encrypt);
            //新增用户
            [OperationContract]
            string addUsers(string encrypt);
            //更新用户
            [OperationContract]
            string updateUsers(string encrypt);

            //获取计划单列表
            [OperationContract]
            string SalesPlanList(string encrypt);
            //获取计量单列表
            [OperationContract]
            string SalesInfoList(string encrypt);
            //更新计划单
            [OperationContract]
            string UpdateSalesPlan(string encrypt);
            //根据计划单号获取计量单列表
            [OperationContract]
            string GetSalesInfoByPlanID(string encrypt);
            //根据固定卡获取计量单
            [OperationContract]
            string GetSalesInfoByCardID(string encrypt);
            //更新计量单状态，签收
            [OperationContract]
            string SalesInfoSign(string encrypt);
            /*
             * 生产、包装入库
             */

            //半成品、产成品手工校验入库并执行打印功能
            [OperationContract]
            string saveProductIn(string encrypt);

            //根据类型获取基本信息
            [OperationContract]
            string getBasicSelectData(string encrypt);

            //生成包材信息
            [OperationContract]
            string savePackingsBill(string encrypt);

            ////按条件查询
            [OperationContract]
            string searchMaterialsInfo(string encrypt);


            /*
            * 生产、包装入库
            */
        }
        public class AppSalesPlan
        {
            //订单FID
            public String FID;
            //订单Number
            public String BillNo;
            //船号
            public String ShipName;

            //预装量
            public Decimal PreQty = 0;
            //实际量
            public Decimal AuxQty = 0;
            //下单日期
            public String PlanTime;
            //计划单状态
            public String PlanState;
            //客户
            public String CustomerName;
            //产品名称
            public String ProductName;
            //归档日期
            public String SuttleTime;
            //产品列表
            //public List<ProductBase> ListProduct = new List<ProductBase>();
        }

        public class AppSalesInfo
        {
            /// <summary>
            /// 单据ID
            /// </summary>
            public int FID = 0;
            /// <summary>
            /// 单据编号
            /// </summary>
            public String BillNo = String.Empty;
            /// <summary>
            /// 步骤
            /// </summary>
            //public int Step;
            public String Step = String.Empty;
            /// <summary>
            /// 第一次计量结果
            /// </summary>
            public Decimal FistValue = 0;
            /// <summary>
            /// 第二次计量结果
            /// </summary>
            public Decimal SecdValue = 0;
            /// <summary>
            /// 打印重量
            /// </summary>
            public Decimal PrintValue = 0;
            /// <summary>
            /// 实际净重
            /// </summary>
            public Decimal AuxSuttle = 0;
            /// <summary>
            /// 核算净重
            /// </summary>
            public Decimal AccSuttle = 0;
            /// <summary>
            /// 历史皮重
            /// </summary>
            public Decimal HisTareQty = 0;

            /// <summary>
            /// 授权人员
            /// </summary>
            public String RightEmp = String.Empty;

            /// <summary>
            /// 授权时间
            /// </summary>
            public String RightTime = String.Empty;

            /// <summary>
            /// 开票人员
            /// </summary>
            public String PlanEmp = String.Empty;
            /// <summary>
            /// 第一次计量人员
            /// </summary>
            public String FistEmp = String.Empty;
            /// <summary>
            /// 第二次计量人员
            /// </summary>
            public String SecdEmp = String.Empty;
            /// <summary>
            /// 登记开票时间
            /// </summary>
            public String PlanTime;
            /// <summary>
            /// 第一次计量时间
            /// </summary>
            public String FistTime;
            /// <summary>
            /// 第二次计量时间
            /// </summary>
            public String SecdTime;

            /// <summary>
            /// 预置皮重
            /// </summary>
            public Decimal PreTare = 0;
            /// <summary>
            /// 车号
            /// </summary>
            public String CarNumber = String.Empty;
            /// <summary>
            /// 识别车号
            /// </summary>
            public String AutoCarNumber = String.Empty;
            /// <summary>
            /// 提货密码
            /// </summary>
            public String PassWord = String.Empty;
            /// <summary>
            /// 备注
            /// </summary>
            public String Note = String.Empty;
            /// <summary>
            /// 批号
            /// </summary>
            public String Batch = String.Empty;
            /// <summary>
            /// 字符戳
            /// </summary>
            public String CharStamp = String.Empty;
            /// <summary>
            /// 校验值
            /// </summary>
            public Decimal CheckValue = 0;
            /// <summary>
            /// 是否填充了数据
            /// </summary>
            public Boolean IsFilled = false;
            /// <summary>
            /// 是否需要称量皮重
            /// </summary>
            public Boolean NeedTareQty = false;

            /// <summary>
            /// 物料
            /// </summary>
            public String ItemName = "";
            public String ItemNumber = "";
            public String ItemID = "";
            //客户
            public String CustomerName;
            /// <summary>
            ///作废标志
            /// </summary>
            public String Cancle;

            /// <summary>
            ///集装箱号
            /// </summary>
            public String ContianerNum;

            /// <summary>
            ///运输方式
            /// </summary>
            public String FetchWay;

            /// <summary>
            ///运输商
            /// </summary>
            public String Logist;

        }
    }

